/*
*	@file	hcomms.cpp
*	@author Artur Gilmutdinov <arturg000@gmail.com>		
*/

#include "hcomms.h"

#define log log_t::log

void hcomm_srv_t::serve_ifs(int socket)
	{
		log("open ifs ");
		char bf[255];
		strcpy(bf,""); 
		// Get object name.
		recv(socket, bf, 255, 0);
		log(bf);
		int aim = -1;
		//cout << node.size();
		// Find object in table.
		log("Nodes ");
		log(inttostr(node.size()));
		for (int i = 0; i<node.size(); i++)
		{
		//pfor_t circle;
		//circle.pfor<hcomm_srv_t>(i, this, &hcomm_srv_t::checkobj, (void*)&pair<char*,int*>(bf, &aim));
		//if (aim>0) circle.pbreak();
		// log (inttostr(node[i]->object.size()));
		 for (int j = 0; j<node[i]->object.size(); j++)
		 {
			log(node[i]->object[j]->name);
		 	if (!strcmp(bf, node[i]->object[j]->name))
			{
				aim = i;
				break;
			}
		 }
		 if (aim>0) break;
		}
		if (aim<0) 
		{ 
			log("No such object"); 
			return; 
		}
		sprintf(bf, "%s\n %d\n", node[aim]->ip, node[aim]->port);
		log("ip");
		log(bf);
		// Send object's ip.
		send(socket, bf, 255, 0);
		close(socket); 
	}
	
void hcomm_srv_t::addnode(int socket, char *ip)
	{
	// check name aviability
	char *bf = new char [255];
	strcpy(bf,"");
	// get name
	recv(socket, bf, 255, 0);
	log("Adding node");
	log(bf);
	/*
	for (int i =0; i<node.size(); i++)
		if (!strcmp(bf, node[i]->name))
		{
			close(socket);
			return;
		}
		*/
		// Create new node.
		node_t *n = new node_t;
		strcpy(n->name, bf);
		strcpy(n->ip, ip);
		node.push_back(n);
		log("added nodes:");
		log(inttostr(node.size()));
		int offport = 0;
		for (int i = 0; i<node.size(); i++)
			if (strsrav(node[i]->ip,ip)) offport++;
		if (cliports.begin+offport>cliports.end)
		{
				log("not enough ports");
				strcpy(bf, "not enough ports\n");
		}
		else 
		{
			sprintf(bf, "%d\n", cliports.begin+offport);	
			log(bf);	
			n->port = cliports.begin+offport;
		}
		
		send (socket, bf, 255, 0);
		close(socket);
	}
	
void hcomm_srv_t::addobj(int socket)
	{
		char *bf = new char [255];
		char *objn = new char [255];
		char bf1[255];
		strcpy(bf,"");
		strcpy(objn,"");
		strcpy(bf1,"");
		// Get node name.
		recv(socket, bf, 255, 0);
		// Get object name.
		recv(socket, objn, 255, 0);
		log("Adding object");
		log(bf);
		log(objn);
		for (int i = 0; i<node.size(); i++)
		// Add record.
		{
			log(node[i]->name);
			if (strsrav(node[i]->name,bf))
			{
				log("ADDED!");
				node[i]->object.push_back(new obj_rec_t(objn, NULL));
				sprintf(bf1, "%s\n", "ok");
				send(socket, bf1, 255, 0);
				close(socket);	
				return;
			}
		}
		log ("ERROR ADDING");
		sprintf(bf1, "%s\n", "error");
		send(socket, bf1, 255, 0);
		//	cout << "added object "<< objn << " at " << bf;
		
		close(socket);
	}